package com.future.common.interceptor;

import com.future.common.annotation.NoNeedLogin;
import com.future.common.exception.AuthenticationException;
import com.future.common.global.PlatFormContext;
import com.future.model.SysUser;
import com.future.service.AuthenticationService;
import com.future.service.SysUserService;
import com.jfinal.aop.Inject;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.StrKit;

import net.minidev.json.JSONObject;

public class AuthenInterceptor implements Interceptor {
	@Inject
	private AuthenticationService authenticationService;
	@Inject
	private SysUserService sysUserService;
	@Override
	public void intercept(Invocation inv) {
		NoNeedLogin noNeedLoginIn = inv.getMethod().getAnnotation(NoNeedLogin.class);
		// 需要登录
		if (noNeedLoginIn == null) {
			String token = inv.getController().getRequest().getHeader("Authorization");
			if (StrKit.isBlank(token)) {
				throw new AuthenticationException("认证信息为空!");
			}
			JSONObject result = this.authenticationService.parseToken(token);
			String userid = result.getAsString("userid");
			SysUser currentUser = this.sysUserService.findUserById(userid);
			if (currentUser == null) {
				throw new AuthenticationException("用户信息不存在!");
			}
			PlatFormContext.setCurrentUser(currentUser);
		}
		inv.invoke();

	}
}
